package master

import (
	"context"
	"encoding/json"
	"gitee.com/zhengjianfeng/crontab-worker/common"
	"go.etcd.io/etcd/clientv3"
	"time"
)

var (
	// 单例
	G_workerJobMgr *WorkerJobMgr
)

// 任务管理器
type WorkerJobMgr struct {
	client *clientv3.Client
	kv     clientv3.KV
	lease  clientv3.Lease
}

// 初始化任务管理器
func InitJobMgr() (err error) {

	var (
		config clientv3.Config
		client *clientv3.Client
		kv     clientv3.KV
		lease  clientv3.Lease
	)

	config = clientv3.Config{
		Endpoints:   G_config.EtcdEndPoints,                                     //集群地址
		DialTimeout: time.Duration(G_config.EtcdDialTimeout) * time.Millisecond, // 超时时间
	}

	// 建立连接
	if client, err = clientv3.New(config); err != nil {
		return
	}

	// 得到kv和lease的API子集
	kv = client.KV
	lease = client.Lease

	// 赋值单例

	G_workerJobMgr = &WorkerJobMgr{
		client: client,
		kv:     kv,
		lease:  lease,
	}

	return
}

// 保存任务
func (workJobMgr *WorkerJobMgr) WorkerSaveJob(workerJob *common.WorkerJob) (oldWorkerJob *common.WorkerJob, err error) {

	var (
		jobKey    string
		jobValue  []byte
		putResp   *clientv3.PutResponse
		oldJobObj common.WorkerJob
	)

	oldJobObj = common.WorkerJob{}

	// etcd中的保存key
	jobKey = common.WORKER_JOB_SAVE_DIR + workerJob.Name

	// 任务信息json
	if jobValue, err = json.Marshal(workerJob); err != nil {
		return
	}

	// 保存到etcd
	if putResp, err = workJobMgr.kv.Put(context.TODO(), jobKey, string(jobValue), clientv3.WithPrevKV()); err != nil {
		return
	}

	// 如果是更新，那么返回值
	if putResp.PrevKv != nil {
		// 对旧值做一个反序列化
		if err = json.Unmarshal(putResp.PrevKv.Value, &oldJobObj); err != nil {
			err = nil
			return
		}
		oldWorkerJob = &oldJobObj
	}
	return
}
